const jwt = require('jsonwebtoken')

const auth = (req, res, next) => {
  try {
    // 从请求头获取token
    const token = req.header('Authorization')?.replace('Bearer ', '')

    if (!token) {
      return res.status(401).json({
        code: 401,
        message: '未提供认证令牌',
        success: false
      })
    }

    // 验证token
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-jwt-secret')
    req.user = decoded
    next()
  } catch (err) {
    res.status(401).json({
      code: 401,
      message: '认证失败',
      success: false
    })
  }
}

module.exports = { auth }
